package com.cloud.pole.shop.rabbit;

/**
 * @Author: Frank Chen
 * @Date: 2020/3/6 11:23
 */

import com.alibaba.fastjson.JSON;
import com.cloud.pole.api.rabbit.DLXMessage;
import com.cloud.pole.common.constant.RebbitConstants;
import com.cloud.pole.shop.constant.ShopCommonConstant;
import com.cloud.pole.shop.model.entity.order.ShopOrder;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 消息队列服务接口实现
 */
@Service
public class RabbitSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 延迟发送消息到队列
     * @param orderSn 订单ID
     */
    public void sendOrder(String orderSn) {
        //消息发送到死信队列上，当消息超时时，会发生到转发队列上，转发队列根据下面封装的queueName，把消息转发的指定队列上
        //发送前，把消息进行封装，转发时应转发到指定 queueName 队列上
        DLXMessage dlxMessage = new DLXMessage(RebbitConstants.REBBIT_SHOP_ORDER_EXCHANGE, RebbitConstants.REBBIT_SHOP_ORDER, orderSn, ShopCommonConstant.SHOP_ORDER_NOT_PAY_MAX_MIN);
        MessagePostProcessor processor = new MessagePostProcessor(){
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration(ShopCommonConstant.SHOP_ORDER_NOT_PAY_MAX_MIN + "");
                return message;
            }
        };
        rabbitTemplate.convertAndSend(RebbitConstants.REBBIT_SHOP_ORDER_EXCHANGE, RebbitConstants.REBBIT_SHOP_ORDER_DEAD_LETTER, JSON.toJSONString(dlxMessage), processor);
    }
    

    /**
     * 发现订单支付成功队列
     * @param order 订单
     */
    public void sendOrderPaySucceed(ShopOrder order) {
        rabbitTemplate.convertAndSend(RebbitConstants.REBBIT_SHOP_ORDER_PAY_SUCCEED, order);
    }
}
